package com.example.module_patrol.ui.addpatrol

import android.content.Intent
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.base.BaseActivity
import com.example.lib_common.utils.ToastUtils
import com.example.module_patrol.R
import com.example.module_patrol.adapter.ImageAdapter
import com.example.module_patrol.databinding.ActivityAddPatrolBinding
import com.example.module_patrol.model.PatrolEntity
import com.example.module_patrol.ui.PatrolViewmodel
import dagger.hilt.android.AndroidEntryPoint
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.io.File



@Route(path = "/patrol/AddPatrolActivity")
@AndroidEntryPoint
class AddPatrolActivity : BaseActivity<PatrolViewmodel, ActivityAddPatrolBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_add_patrol
    private val mViewModel: PatrolViewmodel by viewModels()
    private var back: ImageView? = null
    private var more: ImageView? = null

    private val PICK_IMAGE_REQUEST = 101
    private val TAKE_PHOTO_REQUEST = 102
    private var currentPhotoUri: Uri? = null

    private var photoFile: File? = null // 添加临时文件引用


    private val imageUris = mutableListOf<Uri>()
    private lateinit var imageAdapter: ImageAdapter

    override fun initView() {
        mBinding.commit.setOnClickListener {
            var stands=""
            if (mBinding.etStandard.text.toString().isEmpty()){
                stands="空"
            }else{
                stands=mBinding.etStandard.text.toString()
            }
            val patrolEntity = PatrolEntity(
                id = 0,
                patrolStandard = stands,
                patrolType = mBinding.etType.text.toString(),
                pointImages = "",
                pointLocation = mBinding.etLocation.text.toString(),
                pointName = mBinding.etName.text.toString(),
                projectId = mBinding.etProject.text.toString()
            )
            mViewModel.addPatrol(patrolEntity)
        }
        /*
        返回键
         */
        back = mBinding.topBar3.findViewById(R.id.back)
        back!!.setOnClickListener {
            finish()
        }
        /*
       更多
        */
        more = mBinding.topBar3.findViewById(R.id.more)
        more!!.setOnClickListener {
            ToastUtils.showShort(this, "更多......")
        }
        mBinding.upImg.setOnClickListener {
            showPopupMenu(mBinding.upImg)
        }
        // 初始化RecyclerView
        imageAdapter = ImageAdapter(imageUris)
        mBinding.rv.apply {
            layoutManager = GridLayoutManager(this@AddPatrolActivity, 3)
            adapter = imageAdapter
        }
    }

    override fun initData() {
        mViewModel.addPatrolLiveData.observe(this) {
            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    // 选择图库图片
    // 替换原来的 pickImageFromGallery() 方法
    private fun pickImageFromGallery() {
        val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
            type = "image/*"
            addCategory(Intent.CATEGORY_OPENABLE)
            putExtra(Intent.EXTRA_LOCAL_ONLY, true) // 避免触发云存储的扫描
        }
        startActivityForResult(intent, PICK_IMAGE_REQUEST)
    }

    // 拍照
    // 在拍照方法中移除不必要的媒体扫描
    private fun takePhoto() {
         photoFile = createImageFile().also {
            currentPhotoUri = FileProvider.getUriForFile(
                this,
                "${packageName}.fileprovider",
                it
            )
            Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {
                putExtra(MediaStore.EXTRA_OUTPUT, currentPhotoUri)
                startActivityForResult(this, TAKE_PHOTO_REQUEST)
            }
        }
        // 不再调用 scanFile() 相关方法
    }

    private fun createImageFile(): File {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile("JPEG_${timeStamp}_", ".jpg", storageDir)
    }

    // 修改onActivityResult方法
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                PICK_IMAGE_REQUEST -> {
                    data?.data?.let { uri ->
                        imageUris.add(uri)
                        imageAdapter.notifyItemInserted(imageUris.size - 1)
                        Log.d("poi", uri.path.toString())
                    }
                }

                TAKE_PHOTO_REQUEST -> {
                    currentPhotoUri?.let { uri ->
                        imageUris.add(uri)
                        imageAdapter.notifyItemInserted(imageUris.size - 1)
                        Log.d("poi", uri.path.toString())
                        photoFile=null
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        // 清除Adapter对Context的引用
        mBinding.rv.adapter = null
        photoFile?.delete() // 清理临时文件
        super.onDestroy()
    }
    fun showPopupMenu(view: View) {
        val popup = PopupMenu(this, view) // view 是锚点视图（被点击的按钮等）
        popup.menuInflater.inflate(R.menu.menu_select, popup.menu)

        // 处理菜单项点击
        popup.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.takephone -> {
                    takePhoto()
                    true
                }
                R.id.selectimg->{
                    pickImageFromGallery()
                    true
                }
                else -> false
            }
        }

        // 显示菜单
        popup.show()
    }




}